package com.cg.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.cg.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class AESUtils {

    /**
     * 对明文加密
     *
     * @param content 明文
     * @param key     **
     * @return
     */
    public static String encrypt(String content, String key) {
        //加密为16进制表示
        return getAes(key).encryptHex(content);
    }

    /**
     * 对密文解密
     *
     * @param encryptContent 密文
     * @param key            **
     * @return
     */
    public static String decrypt(String encryptContent, String key) {
        // 解密为字符串
        return getAes(key).decryptStr(encryptContent, CharsetUtil.CHARSET_UTF_8);
    }

    private static AES getAes(String key) {
        if (key != null && key.length() != 16) {
            throw new RuntimeException("**长度需为16位");
        }
        //构建
        return new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes());
    }

    public static void main(String[] args) throws JsonProcessingException {
        User user = User.builder()
                .userName("waaaaa")
                .age(12)
                .build();
        String str = new ObjectMapper().writeValueAsString(user);
        System.out.println(encrypt(str, "44296y971T06yK2x"));
    }
}
